<style rel="stylesheet/scss" lang="scss" scoped>
	.new-pro-table {
		width: 100%;
		display: flex;
		flex: 1;
		flex-direction: column;
		margin-top: 10px;
		position: relative;
		border: 1px solid #E5E5E5;
		.tab-creen {
			width: 100%;
			height: 50px;
			display: flex;
			padding: 0 10px;
			font-size: 14px;
			box-sizing: border-box;
			align-items: center;
		}
		.tab-con {
			flex: 1;
			overflow: auto;
			height: auto;
			position: relative;
			.sc-box {
				min-width: 100%;
				height: 50px;
				display: flex;
				padding: 0 10px;
				align-items: center;
				background: #fff;
				border: 1px solid #ebeef5;
				padding-left: 55px;
			}
		}
		.tab-page {
			width: 100%;
			height: 40px;
			display: flex;
			justify-content: center;
			align-items: center;
			border-top: 1px solid #E5E5E5;
		}
		.area-box {
			resize: none;
			display: block;
			width: 100%;
			padding: 10px;
			height: 300px;
		}
		.el-table{
			min-width: 100%;
		}
	}
</style>
<template>
	<div class="new-pro-table" v-loading.fullscreen.lock="fullscreenLoading">
		<div class="tab-creen">
			<span class="m-r-10">|待选车型</span>
			<el-button type="primary" size="mini" @click="showDiglog">车型ID筛选</el-button>
			<template>
                <el-select class="m-l-10" placeholder="选择品牌" v-model="brandId" @change="getBrandId" size="mini">
                    <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.id">
                    </el-option>
                </el-select>
            </template>
            <template>
                <el-select class="m-l-10" placeholder="选择车系" v-model="seriesId" size="mini">
                    <el-option v-for="item in seriesList" :key="item.id" :label="item.seriesName" :value="item.id">
                    </el-option>
                </el-select>
            </template>
			<el-button size="mini" class="m-l-10" @click="searchList">筛选</el-button>
		</div>
		<div class="tab-con" :style="'width:' + clWidth + 'px'">
			
			<el-table 
				:style="'width:' + clWidth + 'px'"
				ref="multipleTable" :data="modelList" 
				highlight-current-row :fit='false'
				class="el-table"
			    @selection-change="handleSelectionChanges" size="mini">
				<el-table-column type="selection" width="50px" align="center" fixed="left"></el-table-column>
				<el-table-column v-for="tableHeader in modelHead" :label="tableHeader.showName" align="center" width="200px">
					<template slot-scope="scope">
						<div style='width:100%:height:100%;text-align: center;'>
							<span>{{ scope.row[tableHeader.keyId].text }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作"  align="left" width="100">
					<template slot-scope="scope">
						<el-button @click="handleClick(scope.row)" type="text" size="small" style="color:green">添加</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="tab-page">
			 <el-checkbox v-model="checkedVal" @change="setSelectList">全选</el-checkbox>
			 <el-button type="primary" size="mini" class="m-l-10" @click="handleClick(1)">
				 关联{{targetTotal>0?targetTotal: selectTabList.length>0?selectTabList.length:0}}个车型</el-button>
			<current-page :current-page="f_page" :page-size="f_PageSize" :page-total="f_total" @handleCurrentChange="handleTabChange"></current-page>
		</div>
		<!--车型id适配-->
		<el-dialog title="车型ID适配" :visible.sync="centerDialogVisible" width="50%" center>
			<textarea placeholder="车型ID适配" class="area-box" @input="textareaInput" v-model="modelValue"></textarea>
			<span slot="footer" class="dialog-footer">
				<el-button @click="centerDialogVisible = false">取 消</el-button>
				<el-button type="primary"  @click="searchList">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
	import {
		mapMutations,
		mapGetters
	} from 'vuex'
	import {
		SUCCESS_REQUEST_STATUS
	} from '@/utils/config.js'
	import {
		getToken
	} from '@/utils/auth'
	import currentPage from '@/components/current-page/current-page.vue'
	import screening from '../../components/screening.vue'
	export default {
		props: {
			// 商品id
			goodsId: {
				type: String,
				default : '',
			},
			// 二级分类id
			secCatId: {
				type: String,
				default : '',
			}
		},
		data() {
			return {
				f_page: 0,
				f_PageSize: 20,
				f_total: 0,
				modelIds: '',
				modelHead: [],
				cheList: [],
				load: false,
				num: 0,
				totalNum: 0,
				tempId:'',
				targetTempId:'',
				targetTotal:0,
				clWidth: 0,
				brandId: '',
				brandList: [],
				seriesId: '',
				seriesList: [],
				catId: '',
				selList: [],
				modelList: [],
				headTitList: [],
				modelValue: '',
				checkedVal: false,
				selectTabList: [],
				centerDialogVisible: false,
				fullscreenLoading: false
			}
		},
		created() {
			console.log(this.getStepCache)
			this._initProList()
			this._initProHead()
			this.getBrandList()

		},
		mounted() {
			let _this = this
			document.onclick = function () {

				let e = e || window.event
				let el = e.srcElement.className
				if (el !== 'he-input' && el !== 'item-li' && el !== 'item-ul' && el != 'el-checkbox__label' && el !=
					'el-checkbox__original' && el != 'load-more' && el != 'el-checkbox__inner') {
					_this.cheList.forEach((item) => {
						item.showDrep = false
					})
					return
				}
			}
			this.clWidth = document.getElementById('good-containter').clientWidth
		},
		methods: {
			showDiglog() {
				this.modelValue = ''
				this.modelIds = ''
				this.centerDialogVisible = true
			},
			handleClick(item) {
				console.log(item)
				let carIds = ''
				if(item != 1){
					for(let i in item) {
						if(!carIds) {
							carIds = item[i].modelId
						}
					}
				}else{
					
					if(!this.selectTabList.length && !this.targetTotal){
						this.$message({
							type:'error',
							message: '请选择车型进行关联'
						})
						return
					}
					console.log(this.selectTabList)
					if(!this.targetTotal) {
						carIds = this.selectTabList.join(',')
						this.targetTempId = ''
					}
					if(this.targetTotal) {
						this.targetTempId = this.tempId
					}
					
					
				}
				
				if(carIds || this.targetTotal) {
					this.fullscreenLoading = true
					this.$ajax({
						api: 'goods/car/linkadd1',
						params: {
							token: getToken(),
							goodsId: this.getStepCache.goodId,
							carIds: carIds,
							tempId: this.targetTempId,
							gcId: this.getStepCache.gcId ? this.getStepCache.gcId: '',
							merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
						}
					}).then(res => {
						console.log(res)
						this.fullscreenLoading = false
						if(res.status === SUCCESS_REQUEST_STATUS) {
							
							this.$emit('handleLinkFn')
							this.$message({
								type:'success',
								message: '关联成功'
							})
							this.checkedVal = false
							this.targetTotal = 0
							this.targetTempId = ''
							this.selectTabList = []
							
						}
					})
				}
			},
			setSelectList () {
				
				this.targetTotal = this.checkedVal ? this.totalNum	 : 0
				this.selectTabList = []
				
				
				this.modelList.forEach((item, index) => {
					this.$refs.multipleTable.toggleRowSelection(item, false);
					
				})
				console.log(this.checkedVal)
				console.log(this.totalNum)
									
							

				
			},
			getBrandList() {
                this.$ajax({
                    api: 'brands',
					params: {
						token: getToken(),
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
					}
                }).then(res => {
                    console.log(res)
                    if (res.status === 200) {
                        this.brandList = res.data
                    }
                }).catch((err) => {
                    this.$message({
                        type: 'error',
                        message: err.message
                    })
                })
            },
			getBrandId() {
                this.seriesId = ''
                this.$ajax({
                    api: 'series',
                    params: {
						token: getToken(),
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
                        brandId: this.brandId
                    }
                }).then(res => {
                    if (res.status === 200) {
                        this.seriesList = res.data
                    }
                }).catch(err => {
                    this.$message({
                        type: 'error',
                        message: err.message
                    })
                })
            },
			searchList() {
				
				this.centerDialogVisible = false
				this._initProList()
			},
			// 输入车型id
			textareaInput() {
				let ids = []
				ids = this.getModelIds()
				this.modelIds = ids


			},
			getModelIds() {
				let texts = [];
				texts = this.modelValue.split("\n");
				for (var i = 0; i < texts.length; i++) {
					let id = 0
					try {
						id = Number.parseInt(texts[i].trim());
					} catch (error) {}
					if (Number.isNaN(id)) {
						texts.splice(i, 1);
					} else {
						i++;
					}
				}
				return texts;
			},
			initCheList() {
				this.modelHead.forEach((item) => {
					let obj = {
						showDrep: false
					}
					this.cheList.push(obj)

				})
				console.log(this.cheList)
			},
			// 选中
			handleSelectionChanges(val) {
				console.log(val)
				let valueId = ''
				let attr = []
				val.forEach((item) => {
					for (let i in item) {
						attr.push(item[i].modelId)
					}
				})
				//console.log(attr)
				attr = new Set(attr)
				let newArr = Array.from(attr) // 再把set转变成array
				this.selectTabList = newArr
				console.log(newArr)
				this.selectTabList.forEach((item,index) => {
					console.log(item)
					if(item == undefined) {
						this.selectTabList.splice(index, 1)
					}
				})
				this.selList = this.selectTabList
				
				console.log(val.length)
				setTimeout(() =>{
					if(this.selectTabList.length>0){
						this.targetTotal = 0
						this.checkedVal = false
						
					}
				},200)
				console.log(this.selectTabList)
				
			},
			watch: {
				selectTabList(val) {
					console.log(val)
				}
			},
			_initProList(obj) {
				let defaultpra = {
					page: this.f_page,
					pageSize: 20,
					catId: this.getStepCache.secondCartId,
					token: getToken(),
					brand:  this.brandList.length>0 && this.brandId  ? this.brandList.filter((item) => {return this.brandId == item.id})[0].brandName: '' ,
					series: this.seriesList.length>0 && this.seriesId ? this.seriesList.filter((item) => {return this.seriesId == item.id})[0].seriesName: '' ,
					modelIds: this.modelIds,
					merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
				}
				let param = Object.assign({}, defaultpra, obj, this.keyObj)
				this.$ajax({
					api: 'merchant/modelproperty/list',
					params: param
				}).then((res) => {
					console.log(res)
					this.fullscreenLoading = false
					this.modelIds = ''
					if (res.status === 200) {
						console.log(7777)
						console.log(res.data.modelList)
						this.modelList = res.data.modelList
						this.f_total = res.data.page.total
						this.totalNum = res.data.total
						this.tempId = res.data.tempId
						this.targetTempId = this.tempId

					}
				})
			},
			_initProHead() {
				this.$ajax({
					api: 'merchant/modelhead',
					params: {
						token: getToken(),
						catId: this.getStepCache.secondCartId,
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') :
							'',
						showSelected: true
					}
				}).then(res => {
					console.log(res)
					if (res.status === 200) {
// 						res.data.forEach((item, index) => {
// 							if (item.keyId == 'id') {
// 								res.data.splice(index, 1)
// 							}
// 						})
						this.modelHead = res.data
						this.initCheList()
						this.load = true
					}
				})
			},
			// 触发点击页码
			handleTabChange(val) {
				this.f_page = val
				this._initProList()
			},
			// 搜索得到焦点
			handleInput(val) {
				this.getModelheadoption(val, this.modelHead[this.num].keyId)
			},
			filterListFn() {
				let value = this.headTitList.filter((item) => {
					return item.select
				}).map((i) => {
					return i.value
				})
				this.keyObj = {
					[this.keyId]: value.join(',')
				}
				this._initProList()
			},
			getModelheadoption(text = '', keyId) {
				this.keyId = keyId
				this.$ajax({
					api: 'modelheadoption',
					params: {
						keyId: keyId,
						text: text
					}
				}).then(res => {
					this.fullscreenLoading1 = false
					if (res.status === 200) {
						res.data.forEach((item) => {
							item.select = false
						})
						this.headTitList = res.data
					}
					this.time = null
				})
			},
			hideDrep(num) {
				this.cheList.forEach((item) => {
					item.showDrep = false
				})
				this.headTitList = []
				this.num = num
				this.fullscreenLoading1 = true
				this.cheList[num].showDrep = true
				if (this.cheList[num].showDrep) {
					console.log(this.modelHead[num])
					this.getModelheadoption('', this.modelHead[num].keyId)
				}

			},
		},
		components: {
			screening,
			currentPage
		},
		computed: {
			...mapGetters([
				'getStepCache'
			])
		}
	}
</script>
